package com.situ.tos2024.api;

import com.github.pagehelper.PageInfo;
import com.situ.tos2024.model.User;
import com.situ.tos2024.service.UserService;
import com.situ.tos2024.util.JsonResult;
import com.situ.tos2024.util.PaginateInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 功能：用户微服务接口
 *
 * @author 千堆雪
 * @version 1.0.0
 * @since 2023/12/27
 * <p>
 * created by 千堆雪 on 2023/12/27, last modified by 千堆雪 on 2023/12/27
 */
@RestController
@RequestMapping(value = "/api/v1/users", produces = "application/json;charset=utf-8")
public class UserApi {
    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    /**
     * 微服务接口，返回所有用户信息
     */
    @GetMapping
    public JsonResult list(@RequestParam(defaultValue = "1", name = "page") Integer pageNo,
                           @RequestParam(defaultValue = "20", name = "limit") Integer pageSize,
                           User student) {
        //创建一个分页对象
        PaginateInfo pi = PaginateInfo.of(pageNo, pageSize);

        //分页查询用户
        List<User> users = userService.findAll(pi, student);

        //PageHelper的分页对象
        PageInfo<?> pif = pi.getPageInfo();

        return JsonResult.success(pif.getTotal(), users);
    }

    /**
     * 查询唯一用户
     *
     * @param id 目标用户主键
     * @return 用户
     */
    @GetMapping("/{uid}")
    public JsonResult findById(@PathVariable(required = false) Integer uid, Integer id) {
        if (id == null) {
            id = uid;
        }
        if (id == null) {
            return JsonResult.failure("用户编号不可为空");
        }
        User user = userService.findById(id);
        if (user == null) {
            return JsonResult.success(100, "指定编号的用户不存在");
        } else {
            return JsonResult.success(1, user);
        }
    }


    /**
     * 根据用户主键，批量删除
     *
     * @param ids 要批量删除的用户主键
     * @return 成功删除的行数
     */
    @DeleteMapping
    public Map<String, Object> deleteByIds(Integer[] ids) {
        int rows = userService.deleteByIds(ids);//受影响的行数
        return Map.of("success", true, "rows", rows);
    }

    /**
     * 新增用户
     */
    @PostMapping
    public Map<String, Object> save(User student) {
        boolean success = userService.save(student);
        return Map.of("success", success);
    }

    /**
     * 修改用户
     */
    @PatchMapping
    public Map<String, Object> update(User student) {
        boolean success = userService.update(student);
        return Map.of("success", success);
    }
}
